package com.example.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.app.entity.*;
import com.example.app.service.*;
import com.example.common.config.ConfigProperties;
import com.example.common.config.TransWrapper;
import com.example.common.vo.R;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@ToString
@RestController
public class IndexController {

    @Autowired
    private IBannerService bannerService;
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private ISongService songService;
    @Autowired
    private ISongListService songListService;
    @Autowired
    private IListSongService listSongService;
    @Autowired
    private ISingerService singerService;
    @Autowired
    private ICollectService collectService;
    @Autowired
    private ILikedService likedService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IConsumerService consumerService;

    @GetMapping("/banner")
    public Map getBanner(HttpServletRequest request) {

        String type = request.getParameter("type");

        List<Banner> list = bannerService.list();
        if ("local".equals(type)) {
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(e -> e.setPic(e.getPic()));
            }
        } else {
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(e ->
                        e.setPic(configProperties.getNginxBasePath() + e.getPic())
                );
            }
        }
        return TransWrapper.wrap("banners", list);
    }

    /**
     * 个人推荐
     *
     * @param request
     * @return
     */
    @GetMapping("/personalized")
    public Map getRecommend(HttpServletRequest request) {

        QueryWrapper<Song> wrapper = new QueryWrapper<>();

        wrapper.select("name", "pic");

        Page<Song> songPage = new Page<>();

        Page<Song> page = songService.page(songPage, wrapper);

        page.getRecords().forEach(e -> {
            e.setPicUrl(configProperties.getNginxBasePath() + e.getPic());
        });

        return TransWrapper.wrap("result", page.getRecords());
    }

    /**
     * 我尽量不写sql。。。
     * 榜单，歌单代替
     *
     * @param request
     * @return
     */
    @GetMapping("/toplist")
    public Map getToplist(HttpServletRequest request) {

        QueryWrapper<SongList> wrapper = new QueryWrapper<>();

        wrapper.select("title", "pic", "id");

        Page<SongList> songPage = new Page<>();

        songPage.setSize(15);

        Page<SongList> page = songListService.page(songPage, wrapper);

        List<SongList> songLists = page.getRecords();

        songLists.forEach(temp -> {
            temp.setName(temp.getTitle());
            temp.setCoverImgUrl(configProperties.getNginxBasePath() + temp.getPic());
        });
        return TransWrapper.wrap("list", songLists);
    }

    /**
     * 我尽量不写sql。。。
     * 每日推荐
     * @param request
     * @return
     */
    @GetMapping("/recommend/songs")
    public Map getRecommendSongs(HttpServletRequest request) {

        QueryWrapper<Song> wrapper = new QueryWrapper<>();

        wrapper.select("name", "pic" , "id", "singer_id").orderByAsc("RAND()");

        Page<Song> songPage = new Page<>();

        Page<Song> page = songService.page(songPage, wrapper);

        List<Song> records = page.getRecords();

        List<Integer> singerids = records.stream().map(Song::getSingerId).collect(Collectors.toList());

        List<Singer> singers = singerService.listByIds(singerids);

        Map<Integer, Singer> singerMap = singers.stream().collect(Collectors.toMap(Singer::getId, e -> e, (v1, v2) -> v2));

        records.forEach(e -> {
            e.getAl().setName(singerMap.get(e.getSingerId()).getName());
            e.getAl().setPicUrl(configProperties.getNginxBasePath() + e.getPic());
        });
        HashMap<String, Object> stringStringHashMap = new HashMap<>();

        stringStringHashMap.put("dailySongs", records);

        return TransWrapper.wrap("data", stringStringHashMap);
    }

    /**
     * 我尽量不写sql。。。
     * 歌曲详情
     * @param request
     * @return
     */
    @GetMapping("/song/detail")
    public Map getSongDetail(HttpServletRequest request) {

        String idstrs = request.getParameter("ids");

        QueryWrapper<Song> wrapper = new QueryWrapper<>();

        wrapper.select("name", "pic", "singer_id","dt", "id");

        List<Integer> ids = new ArrayList<>();

        ids.add(Integer.parseInt(idstrs));

        wrapper.in("id", ids);

        List<Song> songs = songService.list(wrapper);

        Singer singer = singerService.getById(songs.get(0).getSingerId());

        songs.forEach(e->{
            e.getAr().get(0).setName(singer.getName());
            e.getAl().setPicUrl(configProperties.getNginxBasePath() + e.getPic());
        });

        return TransWrapper.wrap("songs", songs);
    }
    /**
     * 我尽量不写sql。。。
     * 歌曲url
     * @param request
     * @return
     */
    @GetMapping("/song/url")
    public Map getSongUrl(HttpServletRequest request) {

        String idstr = request.getParameter("id");

        QueryWrapper<Song> wrapper = new QueryWrapper<>();

        wrapper.select("url", "id");

        List<Integer> ids = new ArrayList<>();

        ids.add(Integer.parseInt(idstr));

        wrapper.in("id", ids);

        List<Song> songs = songService.list(wrapper);

        songs.forEach(e->{e.setUrl(configProperties.getNginxBasePath() + e.getUrl());});

        return TransWrapper.wrap("data", songs);
    }

    @GetMapping("/song/collectSongList/{userId}")
    public R<List<Song>> isInStarCollect(@PathVariable("userId") Long userId ) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();

        List<Collect> collects = collectService.list(queryWrapper.eq("user_id", userId));
        if(!CollectionUtils.isEmpty(collects)){
            List<Integer> songIds = collects.stream().map(Collect::getSongId).collect(Collectors.toList());
            List<Song> songs = songService.listByIds(songIds);
            List<Integer> singerids = songs.stream().map(Song::getSingerId).collect(Collectors.toList());

            List<Singer> singers = singerService.listByIds(singerids);

            Map<Integer, Singer> singerMap = singers.stream().collect(Collectors.toMap(Singer::getId, e -> e, (v1, v2) -> v2));

            songs.forEach(e -> {
                e.getAl().setName(singerMap.get(e.getSingerId()).getName());
                e.getAl().setPicUrl(configProperties.getNginxBasePath() + e.getPic());
            });
            return R.ok(songs);
        }
        return R.ok(null);
    }

    @PostMapping("/song/isInLikedCollect")
    public R isInLikedCollect(@RequestBody Collect collect ) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Liked> liked = new QueryWrapper<>();
        HashMap<String, Object> hashMap = new HashMap<>();

        Collect col1 = collectService.getOne(queryWrapper.eq("song_id", collect.getSongId())
                .eq("user_id", collect.getUserId()));

        Liked liked1 = likedService.getOne(liked.eq("song_id", collect.getSongId())
                .eq("user_id", collect.getUserId()));

        if(liked1!=null){
            hashMap.put("isLiked",true);
        }else{
            hashMap.put("isLiked",false);
        }

        if(col1!=null){
            hashMap.put("isCollect",true);
        }else{
            hashMap.put("isCollect",false);
        }
        int count = commentService.count(new QueryWrapper<Comment>().eq("song_id", collect.getSongId()));
        hashMap.put("commentCount", count);
        int startCount = likedService.count(new QueryWrapper<Liked>().eq("song_id", collect.getSongId()));
        hashMap.put("startCount", startCount);

        return R.ok(hashMap);
    }

    @PostMapping("/song/addCollect")
    public R addCollect(@RequestBody Collect collect ) {
        collect.setType(0);
        collectService.save(collect);

        return R.ok();
    }

    @PostMapping("/song/removeCollect")
    public R removeCollect(@RequestBody Collect collect) {

        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();

        collectService.remove(queryWrapper.eq("song_id", collect.getSongId())
                .eq("user_id",collect.getUserId()));

        return R.ok();
    }

    @PostMapping("/song/addLiked")
    public R addLiked(@RequestBody Liked liked ) {
        likedService.save(liked);

        return R.ok();
    }

    @PostMapping("/song/removeLiked")
    public R removeLiked(@RequestBody Liked liked) {

        QueryWrapper<Liked> queryWrapper = new QueryWrapper<>();

        likedService.remove(queryWrapper.eq("song_id", liked.getSongId())
                .eq("user_id",liked.getUserId()));

        return R.ok();
    }

    @PostMapping("/song/sendComment")
    public R sendComment(@RequestBody Comment comment) {
        comment.setType(0);
        comment.setUp(0);
        commentService.save(comment);

        return R.ok();
    }

    @GetMapping("/song/getSongComment/{userId}/{songId}")
    public R<List<Comment>> getSongComment(@PathVariable("songId") Long songId ,@PathVariable("userId") Long userId ) {

        List<Comment> comments = commentService.list(new QueryWrapper<Comment>().eq("user_id", userId).eq("song_id", songId)
                .orderByDesc("create_time"));

        if(!CollectionUtils.isEmpty(comments)){
            List<Integer> collect = comments.stream().map(e -> e.getUserId()).collect(Collectors.toList());

            List<Consumer> consumers = consumerService.listByIds(collect);

            Map<Integer, Consumer> consumerMap = consumers.stream().collect(Collectors.toMap(e -> e.getId(), e -> e, (v, v1) -> v1));

            comments.forEach(e->{
                Integer eUserId = e.getUserId();
                if(eUserId!=null){
                    Consumer consumer = consumerMap.get(eUserId);
                    if(consumer!=null){
                        e.setUsername(consumer.getUsername());
                        e.setUserPic(configProperties.getNginxBasePath() + consumer.getAvator());
                    }
                }
            });
        }

        return R.ok(comments);
    }

}
